package com.xlongwei.accounts.controller;

import java.util.List;
import java.util.Objects;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Post;
import org.noear.solon.core.handle.Result;
import org.noear.solon.validation.annotation.Min;
import org.noear.solon.validation.annotation.NotBlank;
import org.noear.solon.validation.annotation.NotNull;
import org.noear.solon.validation.annotation.Pattern;
import org.noear.solon.validation.annotation.Valid;
import com.xlongwei.accounts.dao.MemberDao;
import com.xlongwei.accounts.model.Member;
import cn.dev33.satoken.annotation.SaCheckLogin;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Valid
@Controller
@SaCheckLogin
@Mapping("member")
public class MemberController {
    @Inject
    MemberDao memberDao;

    @Get
    @Post
    @Mapping("list")
    public Result<?> list() {
        Integer userid = UserController.userid();
        List<Member> list = memberDao.list(userid);
        return Result.succeed(list);
    }

    @Post
    @Mapping("create")
    public Result<?> create(@NotBlank @Pattern(UserController.PATTERN_NAME) String name)
            {
        Integer userid = UserController.userid();
        List<Member> list = memberDao.list(userid);
        for (Member account : list) {
            if (name.equals(account.getName())) {
                return Result.failure("名称重复");
            }
        }
        Member Member = new Member();
        Member.setUserid(userid);
        Member.setName(name);
        Integer memberid = memberDao.create(Member);
        Member.setMemberid(memberid);
        log.info("userid={} create memberid={} name={}", userid, memberid, name);
        return Result.succeed(Member);
    }

    @Post
    @Mapping("update")
    public Result<?> update(@NotNull @Min(1) Integer memberid,
            @NotBlank @Pattern(UserController.PATTERN_NAME) String newName)
            {
        Integer userid = UserController.userid();
        Member member = memberDao.retrieve(memberid);
        if (member != null && userid.equals(member.getUserid())
                && !Objects.equals(newName, member.getName())) {
            log.info("userid={} update memberid={} oldName={} newName={}", userid, memberid,
                    member.getName(), newName);
            member.setName(newName);
            memberDao.update(member);
        }
        return Result.succeed(member);
    }
}
